﻿using Company.Core.Logger;
using NModbus;

namespace Company.Plc.NModbus
{
    public class NModbusPlc : PlcBase
    {
        private IModbusMaster master;
        public override bool DoInit()
        {
            try
            {
                tcpClient = new();
                tcpClient.Connect(plcConfig.IP, plcConfig.Port);
                IModbusFactory modbusFactory = new ModbusFactory();
                master = modbusFactory.CreateMaster(tcpClient);
            }
            catch (Exception ex)
            {
                Logs.Error(ex);
            }

            return master != null;
        }

        public override ushort[] Read(string address, ushort length)
        {
            if (ushort.TryParse(address, out var result))
            {
#if DEBUG
                var array = new ushort[length];
                Random random = new Random();
                for (int i = 0; i < length; i++)
                {
                    array[i] = (ushort)random.Next(111, 999);
                    Thread.Sleep(1);
                }
                return array;
#else
                return master.ReadHoldingRegisters(plcConfig.SalveAddress, result, length);
#endif

            }
            else
            {
                return new ushort[0];
            }
        }

        public override bool Write(string address, ushort value)
        {
            if(ushort.TryParse(address, out var result))
            {
                master.WriteSingleRegister(plcConfig.SalveAddress,result,value);
                return true;
            }
            return false;
        }

        public override bool Write(string address, ushort[] value)
        {
            if(ushort.TryParse(address,out var result))
            {
                master.WriteMultipleRegisters(plcConfig.SalveAddress,result,value); 
                return true;
            }
            return false;
        }
    }
}
